import parse from 'mini-html-parser2';
import { request, getImageUrl } from "/utils";
const app = getApp();
Page({
    data: {
        detail: null,
        swiper: [],
        statusBarHeight: 0,
        collapse: true,
        overflow: false,
        ellipsisStyle: 'display: -webkit-box;-webkit-box-orient: vertical;overflow: hidden;text-overflow: ellipsis;-webkit-line-clamp: 2;',
        showCartDetail: false,
        spu: [],
        skuAttributes: [],
        showSku: false,
        sku: [],
        cartList: [],
        cartListStock: 0,
        cartListTotalPrice: 0,
        priceRow: { price: ['00', '0'], originalPrice: ['00', '0'] },
        showClearTips: false,
        goodsRichTextNodes: []
    },
    onLoad({ _id }) {
        this.initPageConfig();
        this.initGoodsInfo(_id);
        this.getCartList();
    },
    initPageConfig() {
        my.setCanPullDown({ canPullDown: false });
        const { statusBarHeight } = app.globalData.sysInfo;
        this.setData({ statusBarHeight });
    },
    async initGoodsInfo(_id) {
        const { code, data: detail } = await request.get('/miniapp/goods/detail', { params: { _id } });
        if (code !== 200) return;
        const { sku, spu } = detail;
        const allSkuAttrs = sku.map(item => item.attributes).flat();
        const newSkuAttrs = [];
        allSkuAttrs.forEach(item => {
            const { key, value } = item;
            const keys = newSkuAttrs.map(item => item.key);
            const includeIndex = keys.indexOf(key);
            if (includeIndex === -1) {
                newSkuAttrs.push({
                    key,
                    valueList: [{
                        ...value,
                        image: getImageUrl(value.image),
                        inStock: true,
                        active: false
                    }]
                })
            } else {
                const valueNames = newSkuAttrs[includeIndex].valueList.map(item => item.name);
                if (!valueNames.includes(value.name)) {
                    newSkuAttrs[includeIndex].valueList.push({
                        ...value,
                        image: getImageUrl(value.image),
                        inStock: true,
                        active: false
                    });
                }
            }
        })
        this.setData({
            detail,
            spu: Object.entries(spu).map((
                [key, value]) => ({
                key,
                valueList: value.map(({ name, image }) => ({
                    name,
                    image: getImageUrl(image)
                }))
            })),
            sku: newSkuAttrs
        });
        if (sku.length) {
            let minPrice = sku[0].price;
            sku.forEach((item) => {
                if (item.price < minPrice) minPrice = item.price;
            });
            const minPriceSkuIndex = sku.findIndex(item => item.price === minPrice);
            sku[minPriceSkuIndex].attributes.forEach((attr) => {
                let _id;
                let find_id = false;
                newSkuAttrs.some(item => {
                    item.valueList.some(item1 => {
                        if (item.key === attr.key && item1.name === attr.value.name && item1.image ===
                            getImageUrl(attr.value.image)) {
                            _id = item1._id
                            find_id = true;
                            return true;
                        }
                    });
                    return find_id;
                })
                this.tapSkuValueItem({ target: { dataset: { _id } } });
            });
        }
        const query = my.createSelectorQuery();
        query.select('.des').boundingClientRect().select('.desText').boundingClientRect().exec(([res1, res2]) => {
            this.setData({
                overflow: res2.height > res1.height
            });
        })
    },
    tapImg({ target: { dataset: { index } } }) {
        my.previewImage({
            urls: this.data.swiper,
            current: index,
            enableSavePhoto: true
        });
    },
    toggleCollapse() {
        this.setData({
            collapse: !this.data.collapse
        });
    },
    tapDes() {
        if (this.data.collapse) {
            this.setData({
                collapse: false
            });
        }
    },
    magnifyAttrImg({ target: { dataset: { image } } }) {
        my.previewImage({ urls: [image] });
    },
    tapSheetLeft() {
        if (!this.data.cartList.length) return;
        this.setData({
            showCartDetail: !this.data.showCartDetail
        });
    },
    tapMask() {
        this.setData({
            showCartDetail: false,
            showSku: false
        });
    },
    handleShowSku() {
        this.setData({
            showSku: true
        });
    },
    getActiveSkuValue(sku) {
        return sku.reduce(((pre, skuItem) => ([...pre, ...skuItem.valueList.filter(item => item.active).map(item => ({
            key: skuItem
                .key,
            value: item
        }))])), []);
    },
    getskuByValueId(_id) {
        let value;
        this.data.detail.sku.some(item => {
            item.attributes.some(item1 => {
                if (item1.value._id === _id) {
                    value = item;
                    return true;
                }
            });
            if (value) return true;
        });
        return value;
    },
    changeSkuAttrs(activeList) {
        const { sku } = this.data.detail;
        if (activeList.length !== this.data.sku.length) return;
        const activeListString = activeList.sort((a, b) => a.key.localeCompare(b.key)).map(item =>
            `${item.key}=${item.value.name}-${item.value.image}`).join('&');
        const attrsStringList = JSON.parse(JSON.stringify(sku)).map(item => item.attributes.sort((a, b) => a.key.localeCompare(b
            .key)).map(item =>
            `${item.key}=${item.value.name}-${getImageUrl(item.value.image)}`).join('&'));
        const skuIndex = attrsStringList.findIndex(item => item === activeListString);
        const price = (sku[skuIndex].price / 100).toFixed(1).split('.');
        const originalPrice = (sku[skuIndex].originalPrice / 100).toFixed(1).split('.');
        this.setData({
            skuAttributes: sku[skuIndex].attributes.map(({ key, value }) => ({
                key,
                value: {
                    ...value,
                    image: getImageUrl(
                        value.image)
                }
            })),
            swiper: sku[skuIndex].images.map(item => getImageUrl(item)),
            priceRow: { price, originalPrice }
        });
        parse(sku[skuIndex].detail.replace(/<img/g, '<img style="width: 100%;"'), (err, nodes) => {
            if (!err) this.setData({
                goodsRichTextNodes: nodes
            });
        })
    },
    tapSkuValueItem({ target: { dataset: { _id, skuIndex } } }) {
        const { sku } = this.data;
        const activeList = this.getActiveSkuValue(sku);
        const activeIds = activeList.map(item => item.value._id);
        let noStock = false;
        sku.some((skuItem) => {
            skuItem.valueList.some(valueItem => {
                if (valueItem._id === _id) {
                    if (!valueItem.inStock) {
                        noStock = true;
                        return true;
                    }
                    skuItem.valueList.forEach(innerValueItem => {
                        innerValueItem.active = false;
                    })
                    valueItem.active = !activeIds.includes(_id);
                    const activeList = this.getActiveSkuValue(sku);
                    this.changeSkuAttrs(activeList);
                    const attributesString = this.data.detail.sku.map(item => item.attributes.reduce((pre, item,
                            index) => pre +
                        `${index?'&':''}${item.key}=${item.value.name}-${getImageUrl(item.value.image)}`, ''
                    ));
                    sku.forEach((innerSkuItem, innerSkuIndex) => {
                        // if (innerSkuIndex === skuIndex && !activeIds.includes(_id)) return;
                        innerSkuItem.valueList.forEach(valueItem => {
                            const currentStringList = [...activeList, {
                                key: innerSkuItem.key,
                                value: valueItem
                            }].map(item =>
                                `${item.key}=${item.value.name}-${item.value.image}`);
                            if (attributesString.some(item => currentStringList.every(
                                    item1 => item.includes(item1)))) {
                                const currentSku = this.getskuByValueId(valueItem._id);
                                const count = currentSku.stock;
                                valueItem.inStock = !!count;
                            } else {
                                valueItem.inStock = false;
                            }
                        })
                    });
                }
            });
            if (noStock) return true;
        });
        this.setData({
            sku
        });
    },
    async getCartList() {
        const { code, data: cartList } = await request.get('/miniapp/shoppingCart/getCartList');
        if (code !== 200) return;
        const cartListStock = cartList.reduce((pre, item) => pre + item.amount, 0);
        const cartListTotalPrice = (cartList.reduce((pre, item) => pre + item.sku.price * item.amount, 0) / 100).toFixed(1);
        this.setData({
            cartList: cartList.map(({ goods, sku, ...item }) => ({
                ...item,
                goods: {
                    ...goods,
                    cover: getImageUrl(goods
                        .cover)
                },
                sku: { ...sku, images: sku.images.map(item => getImageUrl(item)) }
            })),
            cartListStock,
            cartListTotalPrice
        });
    },
    async requestAddAmount(goodsId, skuId, type = 1) {
        my.showLoading({ content: '加载中' });
        try {
            let res;
            if (type === 1) {
                res = await request.post('/miniapp/shoppingCart/addGoodsSku', { goodsId, skuId });
            } else {
                res = await request.delete('/miniapp/shoppingCart/deductGoodsSku', {
                    data: {
                        goodsId,
                        skuId
                    }
                });
            }
            if (res.code === 200) {
                await this.getCartList();
                this.setData({
                    showSku: false
                });
            }
        } finally {
            my.hideLoading();
        }
    },
    async addToCart() {
        const matchedAttrs = [];
        const { sku, detail } = this.data;
        sku.some(skuItem => {
            if (skuItem.valueList.every(valueItem => !valueItem.active)) {
                my.showToast({
                    content: `请选择${skuItem.key}`
                });
                return true;
            }
            skuItem.valueList.some(valueItem => {
                if (valueItem.active) {
                    matchedAttrs.push({ key: skuItem.key, value: valueItem });
                    return true;
                }
            })
        });
        if (matchedAttrs.length < sku.length) return;
        const matchedAttrsString = matchedAttrs.sort((a, b) => a.key.localeCompare(b.key)).map(item =>
            `${item.key}=${item.value.name}-${item.value.image}`).join("&");
        const attrsString = detail.sku.map(item => item.attributes.sort((a, b) => a.key.localeCompare(b.key)).map(item =>
            `${item.key}=${item.value.name}-${getImageUrl(item.value.image)}`).join("&"));
        const skuIndex = attrsString.findIndex(item => item === matchedAttrsString);
        const skuId = detail.sku[skuIndex]._id;
        await this.requestAddAmount(detail._id, skuId);
    },
    cancelClearCart() {
        this.setData({
            showClearTips: false
        });
    },
    async confirmClearCart() {
        my.showLoading({ content: '加载中' });
        try {
            const { code } = await request.delete('/miniapp/shoppingCart/clearCart');
            if (code === 200) {
                await this.getCartList();
                this.setData({
                    showClearTips: false,
                    showCartDetail: false
                });
            }

        } finally {
            my.hideLoading();
        }
    },
    openClearCartModal() {
        this.setData({
            showClearTips: true
        });
    },
    increaseAmount({ target: { dataset: { goodsId, skuId } } }) {
        this.requestAddAmount(goodsId, skuId);
    },
    async descreaseAmount({ target: { dataset: { goodsId, skuId } } }) {
        await this.requestAddAmount(goodsId, skuId, -1);
        if (!this.data.cartList.length) this.setData({
            showCartDetail: false
        });
    },
    goToResult() {
        if (!this.data.cartList.length) return;
        my.navigateTo({ url: '/pages/confirmOrder/confirmOrder' });
    }
});